/**
 * 字节格式化转换
 *
 * @param {Number} bytes 字节大小
 * @param {Object} options 配置项
 * @param {Number} options.decimals 保留小数位数
 * @param {Boolean} options.unitable 是否显示单位
 * @param {String} options.join 单位连接符
 * @returns
 */
export const byteFormate = (bytes, options) => {
  const { decimals = 2, unitable = true, join = " " } = options || {};
  const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  if (bytes === 0) {
    return unitable ? `0${join}B` : 0;
  }
  const k = 1024;
  const index = Math.floor(Math.log(bytes) / Math.log(k));
  const unit = unitable ? `${join}${sizes[index]}` : "";
  const res = (bytes / Math.pow(k, index)).toFixed(decimals);
  return unitable ? `${res}${unit}` : +res;
};

export const colorFormateHex = (value) => {
  const format = (str) => {
    const hex = parseInt(str).toString(16);
    return hex.length === 1 ? `0${hex}` : hex;
  };

  if (value.startsWith("#")) {
    return value; // 如果是16进制颜色，直接返回
  } else if (value.includes("rgb")) {
    const rgb = value.match(/\d+/g);
    const r = format(rgb[0]);
    const g = format(rgb[1]);
    const b = format(rgb[2]);
    const a = rgb[3] ? parseInt(rgb[3]) : 1;
    let hex = `#${r}${g}${b}`;
    if (a !== 1) {
      hex += format(a * 255); // 透明度
    }
    return hex;
  }

  return "";
};
